export const useSort = () => {
  const createdList = (len = 10) => {
    return Array.from({ length: len }, () => Math.floor(Math.random() * 10000))
  }
  const countTime = () => {
    const startTime = Date.now()
    return () => {
      console.log(Date.now() - startTime)
      return Date.now() - startTime
    }
  }
  const bubbleSort = (list: number[], b = true) => {
    for (let i = 0; i < list.length; i++) {
      for (let j = 0; j < list.length - i - 1; j++) {
        if (b) {
          if (list[j] > list[j + 1]) {
            const temp = list[j]
            list[j] = list[j + 1]
            list[j + 1] = temp
          }
        } else {
          if (list[j] < list[j + 1]) {
            const temp = list[j]
            list[j] = list[j + 1]
            list[j + 1] = temp
          }
        }
      }
    }
    return list
  }
  const bubbleSortDemo = (num = 10) => {
    const endTime = countTime()
    const bubblingList = createdList(num)
    bubbleSort(bubblingList, true)
    console.log(bubblingList)
    endTime()
    return bubblingList
  }
  const binarySearch = (list: number[], target: number) => {
    let left = 0
    let right = list.length - 1
    while (left <= right) {
      const mid = Math.floor((left + right) / 2)
      if (list[mid] === target) {
        return mid
      } else if (list[mid] < target) {
        left = mid + 1
      } else {
        right = mid - 1
      }
    }
    return -1
  }
  const timeDemo = (fn = () => ({})) => {
    const endTime = countTime()
    const res = fn()
    endTime()
    return res
  }
  return {
    createdList,
    countTime,
    bubbleSort,
    bubbleSortDemo,
    binarySearch,
    timeDemo
  }
}
